import lombok.Data;
import org.springframework.cloud.context.environment.EnvironmentChangeEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * tcc 变更 发布该事件
 */

public class RichEnvironmentChangeEvent extends EnvironmentChangeEvent {
    private final Map<String, Change> changes;

    public RichEnvironmentChangeEvent(Map<String, Change> changes) {
        super(changes.keySet());
        this.changes = changes;
    }

    public Map<String, Change> getChanges() {
        return changes;
    }

    @Data
    public static class Change {
        private final String newValue;
        private final String oldValue;
        private final Type type;

        public enum Type {
            ADDED,
            MODIFIED,
            DELETED
        }
    }

    public static Map<String, Change> diff(Properties newProps, Properties oldProps) {
        Map<String, Change> changes = new HashMap<>(oldProps.size());
        for (Map.Entry<Object, Object> entry : newProps.entrySet()) {
            String newKey = entry.getKey().toString();
            String newValue = entry.getValue().toString();
            String oldValue = oldProps.get(newKey).toString();
            if (oldValue == null) {
                // 新增
                changes.put(newKey, new Change(newValue, null, Change.Type.ADDED));
            } else if (!newValue.equals(oldValue)) {
                // 修改
                changes.put(newKey, new Change(newValue, oldValue, Change.Type.MODIFIED));
            }
        }

        for (Map.Entry<Object, Object> entry : oldProps.entrySet()) {
            String oldKey = entry.getKey().toString();
            String oldValue = entry.getValue().toString();
            String newValue = newProps.get(oldKey).toString();
            if (newValue == null) {
                //删除
                changes.put(oldKey, new Change(null, oldValue, Change.Type.DELETED));
            }
        }

        return changes;
    }
}
